import React from "react";
import { Button, Input, Form, Notify } from "react-vant";
import axios from "axios";
import { useDispatch } from "react-redux";
import { loginSuccessActionCreator } from "../../store/user/userReducer";
import { useNavigate } from "react-router-dom";
export default () => {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const onFinish = (values: any) => {
    // 请求登录
    axios.post("/api/login", values).then((resp) => {
      const { code, data, message } = resp.data;
      // 没有成功
      if (code !== 200) {
        Notify({ type: "danger", message });
        return;
      }

      // 成功登录
      dispatch(loginSuccessActionCreator(data));
      Notify({ type: "success", message });
      navigate(-1);
    });
  };

  return (
    <Form
      form={form}
      onFinish={onFinish}
      footer={
        <div style={{ margin: "16px 16px 0" }}>
          <Button round nativeType="submit" type="primary" block>
            提交
          </Button>
        </div>
      }
    >
      <Form.Item
        tooltip={{
          message:
            "A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.",
        }}
        rules={[{ required: true, message: "请填写用户名" }]}
        name="username"
        label="用户名"
      >
        <Input placeholder="请输入用户名" />
      </Form.Item>
      <Form.Item
        rules={[{ required: true, message: "请填写密码" }]}
        name="password"
        label="密码"
      >
        <Input placeholder="请输入密码" />
      </Form.Item>
    </Form>
  );
};
